package ChatDemo.rpc.handler;

import ChatDemo.message.RpcRequestMessage;
import ChatDemo.message.RpcResponseMessage;
import ChatDemo.rpc.Service.HelloService;
import ChatDemo.rpc.Service.ServicesFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.Method;

public class RpcRequestMessageHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage msg) throws Exception {
        RpcResponseMessage rpcResponseMessage=new RpcResponseMessage();
        rpcResponseMessage.setSequenceId(msg.getSequenceId());
        try{
            //获取真正的对象
            HelloService service = (HelloService)ServicesFactory.getService(Class.forName(msg.getInterfaceName()));

            //调用方法
            Method method = service.getClass().getMethod(msg.getMethodName(), msg.getParameterTypes());

            //获得返回结果
            Object invoke = method.invoke(service);

            rpcResponseMessage.setReturnValue(invoke);
        }catch (Exception e){
            e.printStackTrace();
            rpcResponseMessage.setExceptionValue(e);
        }

        //无论如何，返回结果
        ctx.writeAndFlush(rpcResponseMessage);
    }
}
